<template>
  <div class="data-manage">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>用户管理</h2>
        <p>管理和查看电商用户信息及行为数据</p>
      </div>
      <div class="header-actions">
        <el-button type="success" :icon="Plus" @click="showAddCustomerDialogHandler">
          添加客户
        </el-button>
        <el-button type="primary" :icon="Upload" @click="showImportDialogHandler">
          导入数据
        </el-button>
        <el-button :icon="Download" @click="exportData" :loading="exportLoading">
          导出数据
        </el-button>
        <el-button :icon="Refresh" @click="refreshData" :loading="dashboardLoading || realtimeLoading">
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 用户统计概览 -->
    <div class="data-overview" v-loading="overviewLoading">
      <el-row :gutter="20">
        <el-col :span="6" v-for="overview in dataOverview" :key="overview.key">
          <el-card class="overview-card" :class="overview.key">
            <div class="overview-content">
              <div class="overview-icon">
                <el-icon :size="28" :color="overview.color">
                  <component :is="overview.icon" />
                </el-icon>
              </div>
              <div class="overview-info">
                <h3>{{ overview.title }}</h3>
                <p class="overview-value">{{ overview.value }}</p>
                <span class="overview-change" :class="overview.trend">
                  <el-icon :size="12">
                    <component :is="overview.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" />
                  </el-icon>
                  {{ overview.change }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filters">
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="用户ID">
            <el-input
              v-model="searchForm.userId"
              placeholder="请输入用户ID"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="性别">
            <el-select
              v-model="searchForm.gender"
              placeholder="请选择性别"
              clearable
              style="width: 120px"
            >
              <el-option label="全部" value="" />
              <el-option label="男性" value="Male" />
              <el-option label="女性" value="Female" />
            </el-select>
          </el-form-item>
          <el-form-item label="地区">
            <el-select
              v-model="searchForm.location"
              placeholder="请选择地区"
              clearable
              style="width: 120px"
            >
              <el-option label="全部" value="" />
              <el-option label="城市" value="Urban" />
              <el-option label="郊区" value="Suburban" />
              <el-option label="农村" value="Rural" />
            </el-select>
          </el-form-item>
          <el-form-item label="偏好分类">
            <el-select
              v-model="searchForm.category"
              placeholder="请选择偏好分类"
              clearable
              style="width: 150px"
            >
              <el-option label="全部" value="" />
              <el-option label="图书" value="Books" />
              <el-option label="电子产品" value="Electronics" />
              <el-option label="服装" value="Apparel" />
              <el-option label="健康美容" value="Health & Beauty" />
              <el-option label="运动" value="Sports" />
              <el-option label="家居园艺" value="Home & Garden" />
              <el-option label="家用 & 厨房" value="Home & Kitchen" />
              <el-option label="玩具" value="Toys" />
              <el-option label="汽车用品" value="Automotive" />
              <el-option label="食品饮料" value="Food & Beverages" />
              <el-option label="时尚" value="Fashion" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">
              搜索
            </el-button>
            <el-button :icon="Refresh" @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 客户价值图例 -->
    <div class="value-legend">
      <el-card>
        <div class="legend-content">
          <div class="legend-title">
            <el-icon><Star /></el-icon>
            <span>客户价值等级</span>
          </div>
          <div class="legend-items">
            <div class="legend-item" v-for="segment in customerValueLegend" :key="segment.name">
              <el-tag
                :color="segment.color"
                size="small"
                :style="{
                  color: segment.textColor,
                  fontWeight: segment.fontWeight,
                  marginRight: '8px'
                }"
              >
                {{ segment.name }}
              </el-tag>
              <span class="legend-desc">{{ segment.desc }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 用户列表 -->
    <div class="data-table">
      <el-card>
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <h3>用户信息列表</h3>
              <span class="data-count">共 {{ totalRecords }} 条记录</span>
            </div>
            <div class="table-actions">
              <el-button
                size="small"
                :icon="Delete"
                type="danger"
                :disabled="selectedRows.length === 0"
                @click="batchDelete"
              >
                批量删除 ({{ selectedRows.length }})
              </el-button>
              <el-button size="small" :icon="Refresh" @click="refreshData">
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          :data="tableData"
          v-loading="tableLoading"
          @selection-change="handleSelectionChange"
          stripe
          border
          style="width: 100%"
          table-layout="auto"
          :row-style="getRowStyle"
        >
          <el-table-column type="selection" width="60" />
          <el-table-column prop="user_id" label="用户ID" width="120" />
          <el-table-column prop="age" label="年龄" width="80" />
          <el-table-column prop="gender" label="性别" width="90">
            <template #default="{ row }">
              <el-tag :type="row.gender === 'Male' ? 'primary' : 'success'" size="small">
                {{ row.gender === 'Male' ? '男' : '女' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="location" label="地区" width="100">
            <template #default="{ row }">
              {{ getLocationText(row.location) }}
            </template>
          </el-table-column>
          <el-table-column prop="income" label="收入" width="150">
            <template #default="{ row }">
              ¥{{ row.income.toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="product_category_preference" label="偏好分类" width="150">
            <template #default="{ row }">
              {{ getCategoryText(row.product_category_preference) }}
            </template>
          </el-table-column>
          <el-table-column prop="total_spending" label="总消费" width="150">
            <template #default="{ row }">
              ¥{{ row.total_spending.toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="customer_value_segment" label="客户价值" width="130">
            <template #default="{ row }">
              <el-tag
                :type="getCustomerValueTagType(row.customer_value_segment)"
                :color="getCustomerValueColor(row.customer_value_segment)"
                size="small"
                :style="{
                  color: getCustomerValueTextColor(row.customer_value_segment),
                  fontWeight: getCustomerValueFontWeight(row.customer_value_segment)
                }"
              >
                {{ row.customer_value_segment }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="activity_level" label="活跃度" width="100">
            <template #default="{ row }">
              <el-tag
                :type="row.activity_level === '高活跃' ? 'success' :
                      row.activity_level === '中活跃' ? 'warning' : 'danger'"
                size="small"
              >
                {{ row.activity_level }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="viewDetail(row)" class="view-btn">
                查看
              </el-button>
              <el-button size="small" type="warning" @click="editRecord(row)" class="edit-btn">
                编辑
              </el-button>
              <el-button size="small" type="danger" link @click="deleteRecord(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalRecords"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="用户详情"
      width="700px"
    >
      <div class="detail-content" v-if="currentRecord">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ currentRecord.user_id }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ currentRecord.age }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentRecord.gender === 'Male' ? '男' : '女' }}</el-descriptions-item>
          <el-descriptions-item label="地区">{{ getLocationText(currentRecord.location) }}</el-descriptions-item>
          <el-descriptions-item label="收入">¥{{ currentRecord.income.toLocaleString() }}</el-descriptions-item>
          <el-descriptions-item label="兴趣爱好">{{ currentRecord.interests.join(', ') }}</el-descriptions-item>
          <el-descriptions-item label="上次登录">{{ currentRecord.last_login_days_ago }} 天前</el-descriptions-item>
          <el-descriptions-item label="购买频率">{{ currentRecord.purchase_frequency }}</el-descriptions-item>
          <el-descriptions-item label="平均订单价值">¥{{ currentRecord.average_order_value.toLocaleString() }}</el-descriptions-item>
          <el-descriptions-item label="总消费">¥{{ currentRecord.total_spending.toLocaleString() }}</el-descriptions-item>
          <el-descriptions-item label="偏好分类">{{ getCategoryText(currentRecord.product_category_preference) }}</el-descriptions-item>
          <el-descriptions-item label="网站停留时间">{{ currentRecord.time_spent_on_site_minutes }} 分钟</el-descriptions-item>
          <el-descriptions-item label="浏览页面数">{{ currentRecord.pages_viewed }}</el-descriptions-item>
          <el-descriptions-item label="订阅通讯">{{ currentRecord.newsletter_subscription ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="客户价值">
            <el-tag
              :type="getCustomerValueTagType(currentRecord.customer_value_segment)"
              :color="getCustomerValueColor(currentRecord.customer_value_segment)"
              size="small"
              :style="{
                color: getCustomerValueTextColor(currentRecord.customer_value_segment),
                fontWeight: getCustomerValueFontWeight(currentRecord.customer_value_segment)
              }"
            >
              {{ currentRecord.customer_value_segment }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="活跃度">
            <el-tag
              :type="currentRecord.activity_level === '高活跃' ? 'success' :
                    currentRecord.activity_level === '中活跃' ? 'warning' : 'danger'"
              size="small"
            >
              {{ currentRecord.activity_level }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- RFM分析详情 -->
        <div v-if="rfmAnalysis" class="rfm-analysis" style="margin-top: 20px;">
          <h4 style="margin-bottom: 16px; color: #409EFF;">
            <el-icon><DataBoard /></el-icon>
            RFM客户价值分析
          </h4>

          <el-row :gutter="20" style="margin-bottom: 16px;">
            <el-col :span="8">
              <el-card class="rfm-card" :style="{ borderTop: `4px solid ${getRfmScoreColor(rfmAnalysis.rfm_analysis.r_score)}` }">
                <div class="rfm-score">
                  <div class="score-value" :style="{ color: getRfmScoreColor(rfmAnalysis.rfm_analysis.r_score) }">
                    {{ rfmAnalysis.rfm_analysis.r_score }}
                  </div>
                  <div class="score-label">R - 最近度</div>
                  <div class="score-desc">{{ rfmAnalysis.explanation.r_score_desc }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="rfm-card" :style="{ borderTop: `4px solid ${getRfmScoreColor(rfmAnalysis.rfm_analysis.f_score)}` }">
                <div class="rfm-score">
                  <div class="score-value" :style="{ color: getRfmScoreColor(rfmAnalysis.rfm_analysis.f_score) }">
                    {{ rfmAnalysis.rfm_analysis.f_score }}
                  </div>
                  <div class="score-label">F - 频率</div>
                  <div class="score-desc">{{ rfmAnalysis.explanation.f_score_desc }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="rfm-card" :style="{ borderTop: `4px solid ${getRfmScoreColor(rfmAnalysis.rfm_analysis.m_score)}` }">
                <div class="rfm-score">
                  <div class="score-value" :style="{ color: getRfmScoreColor(rfmAnalysis.rfm_analysis.m_score) }">
                    {{ rfmAnalysis.rfm_analysis.m_score }}
                  </div>
                  <div class="score-label">M - 金额</div>
                  <div class="score-desc">{{ rfmAnalysis.explanation.m_score_desc }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <el-card class="segment-card">
            <div class="segment-info">
              <div class="segment-title">
                <el-tag
                  :type="getCustomerValueTagType(rfmAnalysis.rfm_analysis.segment)"
                  :color="getCustomerValueColor(rfmAnalysis.rfm_analysis.segment)"
                  size="large"
                  :style="{
                    color: getCustomerValueTextColor(rfmAnalysis.rfm_analysis.segment),
                    fontWeight: getCustomerValueFontWeight(rfmAnalysis.rfm_analysis.segment),
                    fontSize: '16px',
                    padding: '8px 16px'
                  }"
                >
                  {{ rfmAnalysis.rfm_analysis.segment }}
                </el-tag>
                <span class="composite-score">综合评分: {{ rfmAnalysis.rfm_analysis.composite_score }}/5</span>
              </div>
              <div class="segment-desc">{{ rfmAnalysis.explanation.segment_desc }}</div>

              <div class="recommendations" style="margin-top: 12px;">
                <strong>营销建议：</strong>
                <ul style="margin: 8px 0; padding-left: 20px;">
                  <li v-for="rec in rfmAnalysis.explanation.recommendations" :key="rec">{{ rec }}</li>
                </ul>
              </div>
            </div>
          </el-card>
        </div>

        <div v-else-if="rfmLoading" style="text-align: center; margin-top: 20px;">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span style="margin-left: 8px;">正在加载RFM分析...</span>
        </div>
      </div>
    </el-dialog>

    <!-- 导入数据对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="导入数据"
      width="600px"
    >
      <div class="import-content">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        >
          <p>请上传CSV格式的用户数据文件，文件应包含以下字段：</p>
          <p>User_ID, Age, Gender, Location, Income, Interests, Last_Login_Days_Ago, Purchase_Frequency, Average_Order_Value, Total_Spending, Product_Category_Preference, Time_Spent_on_Site_Minutes, Pages_Viewed, Newsletter_Subscription</p>
        </el-alert>

        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :limit="1"
          accept=".csv"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          drag
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">
            将CSV文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传CSV文件，且不超过10MB
            </div>
          </template>
        </el-upload>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button type="primary" @click="handleImportData" :loading="importLoading">
            导入数据
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加客户对话框 -->
    <el-dialog
      v-model="showAddCustomerDialog"
      title="添加客户"
      width="700px"
    >
      <el-form :model="addCustomerForm" label-width="120px" :rules="addCustomerRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID" prop="user_id">
              <el-input v-model="addCustomerForm.user_id" placeholder="请输入用户ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="addCustomerForm.age" :min="1" :max="120" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="addCustomerForm.gender" style="width: 100%">
                <el-option label="男" value="Male" />
                <el-option label="女" value="Female" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区" prop="location">
              <el-select v-model="addCustomerForm.location" style="width: 100%">
                <el-option label="城市" value="Urban" />
                <el-option label="郊区" value="Suburban" />
                <el-option label="农村" value="Rural" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收入" prop="income">
              <el-input-number v-model="addCustomerForm.income" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="偏好分类" prop="product_category_preference">
              <el-select v-model="addCustomerForm.product_category_preference" style="width: 100%">
                <el-option label="图书" value="Books" />
                <el-option label="电子产品" value="Electronics" />
                <el-option label="服装" value="Apparel" />
                <el-option label="健康美容" value="Health & Beauty" />
                <el-option label="运动" value="Sports" />
                <el-option label="家居园艺" value="Home & Garden" />
                <el-option label="家用 & 厨房" value="Home & Kitchen" />
                <el-option label="玩具" value="Toys" />
                <el-option label="汽车用品" value="Automotive" />
                <el-option label="食品饮料" value="Food & Beverages" />
                <el-option label="时尚" value="Fashion" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买频率" prop="purchase_frequency">
              <el-input-number v-model="addCustomerForm.purchase_frequency" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平均订单价值" prop="average_order_value">
              <el-input-number v-model="addCustomerForm.average_order_value" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总消费" prop="total_spending">
              <el-input-number v-model="addCustomerForm.total_spending" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次登录天数" prop="last_login_days_ago">
              <el-input-number v-model="addCustomerForm.last_login_days_ago" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="网站停留时间" prop="time_spent_on_site_minutes">
              <el-input-number v-model="addCustomerForm.time_spent_on_site_minutes" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="浏览页面数" prop="pages_viewed">
              <el-input-number v-model="addCustomerForm.pages_viewed" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="订阅通讯">
          <el-switch v-model="addCustomerForm.newsletter_subscription" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddCustomerDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAddCustomer" :loading="addCustomerLoading">
            添加客户
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑客户对话框 -->
    <el-dialog
      v-model="showEditCustomerDialog"
      title="编辑客户"
      width="700px"
    >
      <el-form :model="editCustomerForm" label-width="120px" :rules="addCustomerRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID" prop="user_id">
              <el-input v-model="editCustomerForm.user_id" placeholder="请输入用户ID" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="editCustomerForm.age" :min="1" :max="120" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="editCustomerForm.gender" style="width: 100%">
                <el-option label="男" value="Male" />
                <el-option label="女" value="Female" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区" prop="location">
              <el-select v-model="editCustomerForm.location" style="width: 100%">
                <el-option label="城市" value="Urban" />
                <el-option label="郊区" value="Suburban" />
                <el-option label="农村" value="Rural" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收入" prop="income">
              <el-input-number v-model="editCustomerForm.income" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="偏好分类" prop="product_category_preference">
              <el-select v-model="editCustomerForm.product_category_preference" style="width: 100%">
                <el-option label="图书" value="Books" />
                <el-option label="电子产品" value="Electronics" />
                <el-option label="服装" value="Apparel" />
                <el-option label="健康美容" value="Health & Beauty" />
                <el-option label="运动" value="Sports" />
                <el-option label="家居园艺" value="Home & Garden" />
                <el-option label="家用 & 厨房" value="Home & Kitchen" />
                <el-option label="玩具" value="Toys" />
                <el-option label="汽车用品" value="Automotive" />
                <el-option label="食品饮料" value="Food & Beverages" />
                <el-option label="时尚" value="Fashion" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买频率" prop="purchase_frequency">
              <el-input-number v-model="editCustomerForm.purchase_frequency" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平均订单价值" prop="average_order_value">
              <el-input-number v-model="editCustomerForm.average_order_value" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总消费" prop="total_spending">
              <el-input-number v-model="editCustomerForm.total_spending" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次登录天数" prop="last_login_days_ago">
              <el-input-number v-model="editCustomerForm.last_login_days_ago" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="网站停留时间" prop="time_spent_on_site_minutes">
              <el-input-number v-model="editCustomerForm.time_spent_on_site_minutes" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="浏览页面数" prop="pages_viewed">
              <el-input-number v-model="editCustomerForm.pages_viewed" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="订阅通讯">
          <el-switch v-model="editCustomerForm.newsletter_subscription" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditCustomerDialog = false">取消</el-button>
          <el-button type="primary" @click="handleEditCustomer" :loading="editCustomerLoading">
            保存修改
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Download, Plus, Search, Refresh, Delete, ArrowUp, ArrowDown,
  DataBoard, User, ShoppingCart, View, Star, Upload, Loading
} from '@element-plus/icons-vue'
import {
  getDataOverview,
  getEcommerceUsersList,
  deleteEcommerceUsers,
  exportEcommerceUsers,
  addEcommerceUser,
  updateEcommerceUser,
  importEcommerceUsers,
  getUserRfmAnalysis
} from '@/api/dashboard'

// 响应式数据
const tableLoading = ref(false)
const overviewLoading = ref(false)
const exportLoading = ref(false)
const showDetailDialog = ref(false)
const showImportDialog = ref(false)
const showAddCustomerDialog = ref(false)
const showEditCustomerDialog = ref(false)
const currentRecord = ref(null)
const rfmAnalysis = ref(null)
const rfmLoading = ref(false)
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const totalRecords = ref(0)

// 搜索表单
const searchForm = ref({
  userId: '',
  gender: '',
  location: '',
  category: ''
})

// 数据概览
const dataOverview = ref([
  {
    key: 'total',
    title: '总记录数',
    value: '1,234,567',
    change: '+12.5%',
    trend: 'up',
    icon: 'DataBoard',
    color: '#409EFF'
  },
  {
    key: 'users',
    title: '活跃用户',
    value: '45,678',
    change: '+8.3%',
    trend: 'up',
    icon: 'User',
    color: '#67C23A'
  },
  {
    key: 'purchases',
    title: '购买行为',
    value: '23,456',
    change: '+15.2%',
    trend: 'up',
    icon: 'ShoppingCart',
    color: '#E6A23C'
  },
  {
    key: 'views',
    title: '浏览行为',
    value: '567,890',
    change: '-2.1%',
    trend: 'down',
    icon: 'View',
    color: '#F56C6C'
  }
])

// 表格数据
const tableData = ref([])

// 导入数据
const importFile = ref(null)
const importLoading = ref(false)

// 添加客户表单
const addCustomerForm = ref({
  user_id: '',
  age: '',
  gender: 'Male',
  location: 'Urban',
  income: '',
  interests: [],
  last_login_days_ago: '',
  purchase_frequency: '',
  average_order_value: '',
  total_spending: '',
  product_category_preference: 'Books',
  time_spent_on_site_minutes: '',
  pages_viewed: '',
  newsletter_subscription: false
})

const addCustomerLoading = ref(false)

// 编辑客户表单
const editCustomerForm = ref({
  user_id: '',
  age: '',
  gender: 'Male',
  location: 'Urban',
  income: '',
  interests: [],
  last_login_days_ago: '',
  purchase_frequency: '',
  average_order_value: '',
  total_spending: '',
  product_category_preference: 'Books',
  time_spent_on_site_minutes: '',
  pages_viewed: '',
  newsletter_subscription: false
})

const editCustomerLoading = ref(false)

// 客户价值图例数据
const customerValueLegend = ref([
  { name: '冠军客户', color: '#FF4D4F', textColor: '#FFFFFF', fontWeight: 'bold', desc: '最优质客户，高频高消费' },
  { name: '忠诚客户', color: '#FF7875', textColor: '#FFFFFF', fontWeight: 'bold', desc: '忠诚度高，定期购买' },
  { name: '潜力客户', color: '#FFA940', textColor: '#FFFFFF', fontWeight: '600', desc: '有提升空间的客户' },
  { name: '有风险客户', color: '#FAAD14', textColor: '#FFFFFF', fontWeight: '600', desc: '活跃度下降，需关注' },
  { name: '新客户', color: '#1890FF', textColor: '#FFFFFF', fontWeight: '500', desc: '新注册或首次购买' },
  { name: '需要关注客户', color: '#40A9FF', textColor: '#FFFFFF', fontWeight: '500', desc: '活跃度和消费下降' },
  { name: '即将流失客户', color: '#91D5FF', textColor: '#666666', fontWeight: 'normal', desc: '长时间未购买' },
  { name: '流失客户', color: '#D9D9D9', textColor: '#666666', fontWeight: 'normal', desc: '已经流失的客户' }
])

// 添加客户表单验证规则
const addCustomerRules = ref({
  user_id: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  income: [
    { required: true, message: '请输入收入', trigger: 'blur' }
  ],
  purchase_frequency: [
    { required: true, message: '请输入购买频率', trigger: 'blur' }
  ],
  average_order_value: [
    { required: true, message: '请输入平均订单价值', trigger: 'blur' }
  ],
  total_spending: [
    { required: true, message: '请输入总消费', trigger: 'blur' }
  ],
  last_login_days_ago: [
    { required: true, message: '请输入上次登录天数', trigger: 'blur' }
  ],
  time_spent_on_site_minutes: [
    { required: true, message: '请输入网站停留时间', trigger: 'blur' }
  ],
  pages_viewed: [
    { required: true, message: '请输入浏览页面数', trigger: 'blur' }
  ]
})

// API调用方法
const loadDataOverview = async () => {
  try {
    overviewLoading.value = true
    const response = await getDataOverview()
    if (response.success) {
      dataOverview.value = response.data.overview
    }
  } catch (error) {
    console.error('加载数据概览失败:', error)
    ElMessage.error('加载数据概览失败')
  } finally {
    overviewLoading.value = false
  }
}

const loadUsersList = async () => {
  try {
    tableLoading.value = true
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      user_id: searchForm.value.userId,
      gender: searchForm.value.gender,
      location: searchForm.value.location,
      category_preference: searchForm.value.category
    }

    const response = await getEcommerceUsersList(params)
    if (response.success) {
      tableData.value = response.data.users
      totalRecords.value = response.data.pagination.total_count
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 方法
const exportData = async () => {
  try {
    exportLoading.value = true
    const params = {
      user_id: searchForm.value.userId,
      gender: searchForm.value.gender,
      location: searchForm.value.location,
      category_preference: searchForm.value.category
    }

    const response = await exportEcommerceUsers(params)

    // 创建下载链接
    const blob = new Blob([response], { type: 'text/csv' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `ecommerce_users_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)

    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  } finally {
    exportLoading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadUsersList()
}

const resetSearch = () => {
  searchForm.value = {
    userId: '',
    gender: '',
    location: '',
    category: ''
  }
  currentPage.value = 1
  loadUsersList()
  ElMessage.success('搜索条件已重置')
}

const refreshData = async () => {
  await Promise.all([
    loadDataOverview(),
    loadUsersList()
  ])
  ElMessage.success('数据已刷新')
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const userIds = selectedRows.value.map(row => row.id)
    const response = await deleteEcommerceUsers(userIds)

    if (response.success) {
      ElMessage.success(response.message)
      selectedRows.value = []
      await loadUsersList()
      await loadDataOverview()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const viewDetail = async (row) => {
  currentRecord.value = row
  showDetailDialog.value = true

  // 加载RFM分析
  await loadRfmAnalysis(row.user_id)
}

// 加载RFM分析
const loadRfmAnalysis = async (userId) => {
  try {
    rfmLoading.value = true
    const response = await getUserRfmAnalysis(userId)

    if (response.success) {
      rfmAnalysis.value = response.data
    } else {
      console.error('获取RFM分析失败:', response.message)
      rfmAnalysis.value = null
    }
  } catch (error) {
    console.error('获取RFM分析失败:', error)
    rfmAnalysis.value = null
  } finally {
    rfmLoading.value = false
  }
}

// 编辑记录
const editRecord = (row) => {
  currentRecord.value = row
  // 填充编辑表单
  editCustomerForm.value = {
    user_id: row.user_id,
    age: row.age,
    gender: row.gender,
    location: row.location,
    income: row.income,
    interests: row.interests || [],
    last_login_days_ago: row.last_login_days_ago,
    purchase_frequency: row.purchase_frequency,
    average_order_value: row.average_order_value,
    total_spending: row.total_spending,
    product_category_preference: row.product_category_preference,
    time_spent_on_site_minutes: row.time_spent_on_site_minutes,
    pages_viewed: row.pages_viewed,
    newsletter_subscription: row.newsletter_subscription
  }
  showEditCustomerDialog.value = true
}

// 显示导入对话框
const showImportDialogHandler = () => {
  showImportDialog.value = true
}

// 显示添加客户对话框
const showAddCustomerDialogHandler = () => {
  // 重置表单
  addCustomerForm.value = {
    user_id: '',
    age: '',
    gender: 'Male',
    location: 'Urban',
    income: '',
    interests: [],
    last_login_days_ago: '',
    purchase_frequency: '',
    average_order_value: '',
    total_spending: '',
    product_category_preference: 'Books',
    time_spent_on_site_minutes: '',
    pages_viewed: '',
    newsletter_subscription: false
  }
  showAddCustomerDialog.value = true
}

// 处理文件选择
const handleFileChange = (file) => {
  importFile.value = file.raw
}

// 处理文件移除
const handleFileRemove = () => {
  importFile.value = null
}

// 处理导入数据
const handleImportData = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的CSV文件')
    return
  }

  try {
    importLoading.value = true

    const response = await importEcommerceUsers(importFile.value)

    if (response.success) {
      ElMessage.success(response.message)
      showImportDialog.value = false
      importFile.value = null

      // 刷新数据
      await loadUsersList()
      await loadDataOverview()
    } else {
      ElMessage.error(response.message)
    }

  } catch (error) {
    console.error('导入数据失败:', error)
    ElMessage.error('导入数据失败')
  } finally {
    importLoading.value = false
  }
}

// 处理添加客户
const handleAddCustomer = async () => {
  try {
    addCustomerLoading.value = true

    const response = await addEcommerceUser(addCustomerForm.value)

    if (response.success) {
      ElMessage.success(response.message)
      showAddCustomerDialog.value = false

      // 刷新数据
      await loadUsersList()
      await loadDataOverview()
    } else {
      ElMessage.error(response.message)
    }

  } catch (error) {
    console.error('添加客户失败:', error)
    ElMessage.error('添加客户失败')
  } finally {
    addCustomerLoading.value = false
  }
}

// 处理编辑客户
const handleEditCustomer = async () => {
  try {
    editCustomerLoading.value = true

    const response = await updateEcommerceUser(currentRecord.value.user_id, editCustomerForm.value)

    if (response.success) {
      ElMessage.success(response.message)
      showEditCustomerDialog.value = false

      // 刷新数据
      await loadUsersList()
      await loadDataOverview()
    } else {
      ElMessage.error(response.message)
    }

  } catch (error) {
    console.error('更新客户失败:', error)
    ElMessage.error('更新客户失败')
  } finally {
    editCustomerLoading.value = false
  }
}



const deleteRecord = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${row.user_id} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteEcommerceUsers([row.id])

    if (response.success) {
      ElMessage.success(response.message)
      await loadUsersList()
      await loadDataOverview()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 地区中文转换
const getLocationText = (location) => {
  const locationMap = {
    'Urban': '城市',
    'Suburban': '郊区',
    'Rural': '农村'
  }
  return locationMap[location] || location
}

// 分类中文转换
const getCategoryText = (category) => {
  const categoryMap = {
    'Books': '图书',
    'Electronics': '电子产品',
    'Apparel': '服装',
    'Health & Beauty': '健康美容',
    'Sports': '运动',
    'Home & Garden': '家居园艺',
    'Home & Kitchen': '家用 & 厨房',
    'Toys': '玩具',
    'Automotive': '汽车用品',
    'Food & Beverages': '食品饮料',
    'Fashion': '时尚'
  }
  return categoryMap[category] || category
}

// 获取客户分群标签类型
const getSegmentTagType = (segment) => {
  const segmentTypes = {
    '冠军客户': 'danger',
    '忠诚客户': 'success',
    '潜力客户': 'primary',
    '新客户': 'info',
    '有风险客户': 'warning',
    '需要关注客户': 'warning',
    '即将流失客户': 'danger',
    '流失客户': 'info'
  }
  return segmentTypes[segment] || 'info'
}

// 客户价值等级定义（从高到低）
const getCustomerValueLevel = (segment) => {
  const valueLevels = {
    '冠军客户': 8,      // 最高价值
    '忠诚客户': 7,      // 高价值
    '潜力客户': 6,      // 较高价值
    '有风险客户': 5,    // 中等价值
    '新客户': 4,        // 中等价值
    '需要关注客户': 3,  // 较低价值
    '即将流失客户': 2,  // 低价值
    '流失客户': 1       // 最低价值
  }
  return valueLevels[segment] || 1
}

// 获取客户价值标签类型
const getCustomerValueTagType = (segment) => {
  const level = getCustomerValueLevel(segment)
  if (level >= 7) return 'danger'      // 高价值：红色
  if (level >= 5) return 'warning'     // 中价值：橙色
  if (level >= 3) return 'primary'     // 较低价值：蓝色
  return 'info'                        // 低价值：灰色
}

// 获取客户价值背景颜色（渐变色，价值越高越鲜艳）
const getCustomerValueColor = (segment) => {
  const level = getCustomerValueLevel(segment)
  const colors = {
    8: '#FF4D4F', // 冠军客户：鲜红色
    7: '#FF7875', // 忠诚客户：红色
    6: '#FFA940', // 潜力客户：橙色
    5: '#FAAD14', // 有风险客户：黄色
    4: '#1890FF', // 新客户：蓝色
    3: '#40A9FF', // 需要关注客户：浅蓝色
    2: '#91D5FF', // 即将流失客户：更浅蓝色
    1: '#D9D9D9'  // 流失客户：灰色
  }
  return colors[level] || colors[1]
}

// 获取客户价值文字颜色
const getCustomerValueTextColor = (segment) => {
  const level = getCustomerValueLevel(segment)
  // 高价值客户使用白色文字，低价值客户使用深色文字
  return level >= 4 ? '#FFFFFF' : '#666666'
}

// 获取客户价值字体粗细
const getCustomerValueFontWeight = (segment) => {
  const level = getCustomerValueLevel(segment)
  // 价值越高字体越粗
  if (level >= 7) return 'bold'
  if (level >= 5) return '600'
  if (level >= 3) return '500'
  return 'normal'
}

// 获取表格行样式（根据客户价值设置背景色）
const getRowStyle = ({ row }) => {
  const level = getCustomerValueLevel(row.customer_value_segment)
  const backgroundColors = {
    8: 'rgba(255, 77, 79, 0.08)',   // 冠军客户：淡红色背景
    7: 'rgba(255, 120, 117, 0.06)', // 忠诚客户：更淡的红色
    6: 'rgba(255, 169, 64, 0.06)',  // 潜力客户：淡橙色
    5: 'rgba(250, 173, 20, 0.05)',  // 有风险客户：淡黄色
    4: 'rgba(24, 144, 255, 0.04)',  // 新客户：淡蓝色
    3: 'rgba(64, 169, 255, 0.03)',  // 需要关注客户：更淡蓝色
    2: 'rgba(145, 213, 255, 0.02)', // 即将流失客户：很淡蓝色
    1: 'rgba(217, 217, 217, 0.02)'  // 流失客户：很淡灰色
  }

  return {
    backgroundColor: backgroundColors[level] || backgroundColors[1]
  }
}

// 获取RFM评分颜色（1-5分对应不同颜色强度）
const getRfmScoreColor = (score) => {
  const colors = {
    5: '#FF4D4F', // 5分：鲜红色（最好）
    4: '#FF7875', // 4分：红色
    3: '#FFA940', // 3分：橙色
    2: '#40A9FF', // 2分：蓝色
    1: '#D9D9D9'  // 1分：灰色（最差）
  }
  return colors[score] || colors[1]
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadUsersList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUsersList()
}

// 生命周期
onMounted(async () => {
  console.log('用户管理页面已挂载')
  try {
    await loadDataOverview()
    await loadUsersList()
  } catch (error) {
    console.error('页面初始化失败:', error)
    ElMessage.error('页面加载失败，请刷新重试')
  }
})
</script>

<style scoped>
.data-manage {
  padding: 0;
  background-color: transparent;
  width: 100%;
  min-width: 1200px; /* 确保表格有足够的最小宽度 */
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 数据概览 */
.data-overview {
  margin-bottom: 24px;
}

.overview-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}

.overview-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.overview-card:hover::before {
  opacity: 1;
}

.overview-card.total::before {
  background: linear-gradient(90deg, #409EFF, #5dade2);
}

.overview-card.users::before {
  background: linear-gradient(90deg, #67C23A, #58d68d);
}

.overview-card.purchases::before {
  background: linear-gradient(90deg, #E6A23C, #f7dc6f);
}

.overview-card.views::before {
  background: linear-gradient(90deg, #F56C6C, #ec7063);
}

.overview-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
}

.overview-icon {
  padding: 12px;
  border-radius: 12px;
  background: rgba(64, 158, 255, 0.1);
}

.overview-info h3 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.overview-value {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.overview-change {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.overview-change.up {
  color: #67C23A;
}

.overview-change.down {
  color: #F56C6C;
}

/* 搜索筛选 */
.search-filters {
  margin-bottom: 24px;
}

.search-filters .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

/* 数据表格 */
.data-table {
  width: 100%;
}

.data-table .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  width: 100%;
}

.data-table .el-table {
  width: 100%;
}

.data-table .el-card__body {
  padding: 20px;
}

/* 确保表格占满宽度 */
.data-table .el-table__body-wrapper {
  width: 100% !important;
}

.data-table .el-table__header-wrapper {
  width: 100% !important;
}

/* 表格行样式优化 */
.data-table .el-table__row {
  height: 60px;
}

.data-table .el-table__cell {
  padding: 12px 8px;
  vertical-align: middle;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.data-count {
  color: #666;
  font-size: 14px;
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框 */
.detail-content {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .data-overview .el-col {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-actions {
    justify-content: center;
  }

  .overview-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .table-header {
    flex-direction: column;
    gap: 12px;
  }

  .table-actions {
    justify-content: center;
  }

  .search-filters .el-form {
    flex-direction: column;
  }

  .search-filters .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
}

@media (max-width: 480px) {
  .data-manage {
    padding: 0 16px;
  }

  .page-header {
    padding: 16px;
  }

  .overview-content {
    padding: 16px;
  }

  .data-count {
    font-size: 12px;
  }
}

/* 查看按钮样式 */
.view-btn {
  color: white !important;
  background-color: #409EFF !important;
  border-color: #409EFF !important;
}

.view-btn:hover {
  background-color: #66b1ff !important;
  border-color: #66b1ff !important;
  color: white !important;
}

.view-btn:focus {
  background-color: #409EFF !important;
  border-color: #409EFF !important;
  color: white !important;
}

/* 编辑按钮样式 */
.edit-btn {
  color: white !important;
  background-color: #E6A23C !important;
  border-color: #E6A23C !important;
  margin-left: 8px;
}

.edit-btn:hover {
  background-color: #ebb563 !important;
  border-color: #ebb563 !important;
  color: white !important;
}

.edit-btn:focus {
  background-color: #E6A23C !important;
  border-color: #E6A23C !important;
  color: white !important;
}

/* RFM分析样式 */
.rfm-analysis {
  border-top: 1px solid #EBEEF5;
  padding-top: 20px;
}

.rfm-card {
  text-align: center;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.rfm-score {
  padding: 16px;
}

.score-value {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.score-label {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.score-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.segment-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.segment-info {
  padding: 16px;
}

.segment-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.composite-score {
  font-size: 14px;
  color: #666;
  font-weight: bold;
}

.segment-desc {
  color: #666;
  line-height: 1.6;
  margin-bottom: 12px;
}

.recommendations {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.recommendations ul {
  margin: 8px 0;
  color: #555;
}

.recommendations li {
  margin-bottom: 4px;
}

/* 客户价值图例样式 */
.value-legend {
  margin-bottom: 24px;
}

.value-legend .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.legend-content {
  padding: 16px;
}

.legend-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.legend-title .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.legend-items {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.legend-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

/* 表格行悬停效果增强 */
.data-table .el-table__row:hover {
  background-color: rgba(64, 158, 255, 0.1) !important;
}

/* 高价值客户行特殊样式 */
.data-table .el-table__row.high-value-customer {
  border-left: 4px solid #FF4D4F;
}

.data-table .el-table__row.medium-value-customer {
  border-left: 4px solid #FFA940;
}

.data-table .el-table__row.low-value-customer {
  border-left: 4px solid #91D5FF;
}
</style>
